package com.atguitu.campus.renwendemo.Controller;

import com.atguitu.campus.renwendemo.utils.AjaxResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/api")
public class ImageUploadController {

    @Value("${upload.path}")
    private String uploadPath;

    @PostMapping("/upload")
    public AjaxResult uploadImage(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return AjaxResult.error("请选择要上传的图片");
        }

        try {
            // 生成唯一文件名，避免冲突
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String uniqueFilename = UUID.randomUUID().toString() + fileExtension;

            // 确保上传目录存在
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            // 保存文件
            File dest = new File(uploadPath + "/" + uniqueFilename);
            file.transferTo(dest);

            // 返回文件访问路径（实际项目中可能需要返回完整URL）
            return AjaxResult.success("文件上传成功",uniqueFilename);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("上传失败，请重试");
        }
    }
}
